const crypto = require("crypto");
// 加密形式
const algorithm = "aes-128-cbc";
// 密钥
const key = Buffer.from("acdv1pu6q0xm6k1t");
const iv = Buffer.from(
  Math.random().toString(36).slice(-8) + Math.random().toString(36).slice(-8)
);
// console.log('key', key)
// console.log('crypto', crypto.getCiphers()) // 支持的加密格式列表

const encrypt = (str) => {
  const crypt = crypto.createCipheriv(algorithm, key, iv);
  let crypted = crypt.update(str, "utf8", "hex");
  // console.log("crypted", crypted);
  crypted += crypt.final("hex");
  // console.log("crypted", crypted);
  return crypted;
};

const decrypt = (signed, key, iv) => {
  const dec = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = dec.update(signed, "hex", "utf8");
  decrypted += dec.final("utf8");
  return decrypted;
};

module.exports = {
  encrypt,
  decrypt,
};
